/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package controller;

import static controller.BusControl.getApplications;
import docs.InternshipCompanyModel;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpSession;
import model.Applications;
import model.Company;
import model.Notification;
import model.Student;
import model.Utilisateur;
import org.netbeans.xml.schema.elements.APPLICATION;
import org.netbeans.xml.schema.elements.APPLICATIONTYPE;
import org.netbeans.xml.schema.elements.COMPANYTYPE;
import org.netbeans.xml.schema.elements.LISTIDTYPE;
import org.netbeans.xml.schema.elements.NOTIF;
import org.netbeans.xml.schema.elements.NOTIFSTYPE;
import org.netbeans.xml.schema.elements.PERSONNELTYPE;
import org.netbeans.xml.schema.elements.STUDENTTYPE;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

/**
 *
 * @author metbill
 */
@Controller
public class HomeController {
    
    /**
     * Disconnection
     * @param model
     * @param session
     * @return 
     */
    @RequestMapping(value = "/disconnect", method = RequestMethod.GET)
    public String disconnect (ModelMap model,HttpSession session) {
        //détruire la session
        session.invalidate();
        return "connection";
    }
    
    /**
     * Go to the home page
     * Student : list of candidatures, search internship
     * Supervisor: list of candidatures
     * Company: list of offers
     * @param model
     * @param session
     * @return 
     */
    @RequestMapping(value = "/home", method = RequestMethod.GET)
    public String home (ModelMap model,HttpSession session) {

        int tip = (int) session.getAttribute("userType");
        int idUser = (int) session.getAttribute("userID");
        
        
                 if (tip == 1) {
                     // Gestion de la connection de l'étudiant
                     
                   STUDENTTYPE stud = BusControl.getStudentbyId(idUser);
                   
                    // Màj du nombre de notifications
                    NOTIFSTYPE test = BusControl.getNotifications(idUser);
                    int notifs = test.getNOTIFS().size();
                    
                    //mise à jour de la liste de candidature
                    APPLICATIONTYPE listCand = getApplications(idUser);
                    ArrayList<Applications> listCan= new ArrayList<>();
                    
                    if (listCand != null){
                    Iterator<APPLICATION> ite = listCand.getAPPLICATIONS().iterator();
                     while (ite.hasNext()){
                         APPLICATION offer = ite.next();
                         InternshipCompanyModel inte = BusControl.getOffersById(BusControl.getAppById(offer.getApplicationID()).getInternshipID());
                          int statusId=BusControl.getAppById(offer.getApplicationID()).getStatus();
                          String status = Utils.getStatus(statusId);
                         COMPANYTYPE com = BusControl.getCompanybyId(offer.getCompanyID());
                         
                         Applications can = new Applications(offer.getApplicationID(),null,inte, com.getNOM(), com.getMAIL(), com.getADDRESS(), status);
                         //listCan.add(can);
                         can.setStatusId(statusId);
                         //int stat = BusControl.getAppById(can.getApplicationId()).getStatus();
                         //On n'affiche pas les stages refuse par l'etudiant
                         if (statusId != 4){              
                            listCan.add(can);           
                         }
                     }
                    } else {
                        listCan = null;
                    }
                    model.addAttribute("id","3");
                    model.addAttribute("listCan", listCan);
                    Utils.drawHomePage(stud.getFIRSTNAME().toString(), notifs, "searchStudent", "candidatureStudent", model);
                    
                }else if (tip == 3 ){
                  // Gestion de la connection de la company 
                    
                    COMPANYTYPE comp = BusControl.getCompanybyId(idUser);
                    
                    //Gestion des notifications
                    NOTIFSTYPE test = BusControl.getNotifications(idUser);
                    int notifs = test.getNOTIFS().size();
                    
                    //Gestion de la liste des offres disponibles
                    List<InternshipCompanyModel> offers = BusControl.getOffers(null);
                    Utils.drawHomePageCompany(comp.getNOM().toString(), notifs,  "blank","internshipsCompany", model, offers);            
             
                }else if (tip == 2) {
                     // Gestion de la connection du supervisor
                    
                   PERSONNELTYPE superv = BusControl.getPersonnelbyId(idUser);
                   NOTIFSTYPE test = BusControl.getNotifications(idUser);
                   int notifs = test.getNOTIFS().size();
                   //Gestion de la liste de demande de stages à accepter.
                   
                   LISTIDTYPE students = BusControl.getStudentsSupervisor(idUser);
                        List<Integer> studentsIds = students.getID();
                        ArrayList<Applications> listCan= new ArrayList<>();
                        
                        for (Integer studId : studentsIds) {
                            STUDENTTYPE stud = BusControl.getStudentbyId(studId);
                            Student student = new Student(studId,(String)stud.getFIRSTNAME(), (String)stud.getLASTNAME(), (String)stud.getMAIL(), (String)stud.getPHONENUMBER(), Integer.valueOf((String)stud.getSUPERVISORID()));
                            
                            APPLICATIONTYPE listCand = getApplications(studId);
                            if (listCand != null){
                                Iterator<APPLICATION> ite = listCand.getAPPLICATIONS().iterator();
                                
                                while (ite.hasNext()){
                                    APPLICATION offer = ite.next();
                                    
                                    
                                    int appId = offer.getApplicationID();
                                    int status = BusControl.getAppById(appId).getStatus();
                                    
                                    InternshipCompanyModel inte = BusControl.getOffersById(BusControl.getAppById(appId).getInternshipID());
                                    
                                    COMPANYTYPE com = BusControl.getCompanybyId(offer.getCompanyID());
                                    Applications can = new Applications(appId,student,inte, com.getNOM(), com.getMAIL(), com.getADDRESS(), Utils.getStatus(status));
                                                                        
                                    //If status est entre [8,11), on ajoute dans la liste des candidatures
                                    //int stat = BusControl.getAppById(can.getApplicationId()).getStatus();
                                    if (status >= 8 && status <11){
                                        listCan.add(can);
                                    }
                                    //listCan.add(can);
                                }
                            }
                        }
                        model.addAttribute("listCan", listCan);

                   Utils.drawHomePage(session.getAttribute("userName").toString(), notifs, "generateAccount", "candidatureSupervisor", model);
                }
        return "home";
    }
    
    /**
     * Display the notifications
     * @param model
     * @param session
     * @return 
     */
        @RequestMapping(value = "/notification", method = RequestMethod.GET)
    public String notification (ModelMap model, HttpSession session) {
        
        if (session.getAttribute("userID") != null ){ 
            int idUser = (int) session.getAttribute("userID");
            
           // Gestion de la liste de notification
             NOTIFSTYPE test = BusControl.getNotifications(idUser);
             Iterator<NOTIF> ite = test.getNOTIFS().iterator();
             ArrayList<Notification> listNot = new ArrayList<Notification>();
             while (ite.hasNext()){
                 NOTIF nono = ite.next();
                 Notification not = new Notification(nono.getIDFROM(),nono.getMESSAGE());
                 System.out.println(not.getMessage());
                 listNot.add(not);
             }
             int notifs = test.getNOTIFS().size();
             model.addAttribute("notifications", listNot);
             String pageGauche = null;
             
             //Gestion du réaffichage en fonction du profil de l'utilisateur
             if ((int)session.getAttribute("userType") == 1){
                 pageGauche = "searchStudent";
             } else if ((int)session.getAttribute("userType") == 3){
                 //List<InternshipCompanyModel> offers = BusControl.getOffers(null);
                 //model.addAttribute("offers",offers);
                 //pageGauche = "internshipsCompany";
                 pageGauche = "blank";
             }
             else{
                 pageGauche = "generateAccount";
             }
             Utils.drawHomePage(session.getAttribute("userName").toString(), notifs, pageGauche, "notifs", model);
                        
        } else {
            model.addAttribute("errormessage", " You need to be authenticated.");
            return "connection";
        }
        return "home";
    }
    
    /**
     * Write a notification
     * @param model
     * @param session
     * @return 
     */
     @RequestMapping(value = "/writeNotif/{id}", method = RequestMethod.GET)
    public String writeNotif (@PathVariable("id") int id,ModelMap model, HttpSession session) {
        
        if (session.getAttribute("userID") != null ){ 
            int idUser = (int) session.getAttribute("userID");
             NOTIFSTYPE test = BusControl.getNotifications(idUser);
             Iterator<NOTIF> ite = test.getNOTIFS().iterator();
             ArrayList<Notification> listNot = new ArrayList<Notification>();
             while (ite.hasNext()){
                 NOTIF nono = ite.next();
                 Notification not = new Notification(nono.getIDFROM(),nono.getMESSAGE());
                 listNot.add(not);
             }
            
             int notifs = test.getNOTIFS().size();
             model.addAttribute("notifications", listNot);
                     
             //id du destinataire
             if ((int) session.getAttribute("userID") == 3){
                   int ID = 0;
                  model.addAttribute("idTo",ID);
             } else {
                  model.addAttribute("idTo",id);
             }
             System.out.println("LA notif sera envoyée à :"+id);
             Utils.drawHomePage(session.getAttribute("userName").toString(), notifs, "writeNotif", "notifs", model);
                        
        } else {
            model.addAttribute("errormessage", " You need to be authenticated.");
            return "connection";
        }
        return "home";
    }
    
    /**
     * Send a notification
     * @param noti
     * @param model
     * @param session
     * @return 
     */
     @RequestMapping(value = "/sendNotif", method = RequestMethod.POST)
     public String sendNotif (@ModelAttribute("SpringWeb") Notification noti  , ModelMap model, HttpSession session) {
        
        if (session.getAttribute("userID") != null ){ 
            
            System.out.println("id to :"+noti.getIdTo());
            System.out.println("id to :"+session.getAttribute("userID"));
           BusControl.creerNotification(noti.getIdTo(), (int) session.getAttribute("userID"), noti.getMessage());
 
            int idUser = (int) session.getAttribute("userID");
             NOTIFSTYPE test = BusControl.getNotifications(idUser);
             Iterator<NOTIF> ite = test.getNOTIFS().iterator();
             ArrayList<Notification> listNot = new ArrayList<Notification>();
            
             while (ite.hasNext()){
                 NOTIF nono = ite.next();
                 Notification not = new Notification(nono.getIDFROM(),nono.getMESSAGE());
                 listNot.add(not);
             }
             int notifs = test.getNOTIFS().size();
             model.addAttribute("notifications", listNot);
             model.addAttribute("errormessage", "Sending ok"); 
                 model.addAttribute("errormessage", "Sending ok");
             Utils.drawHomePage(session.getAttribute("userName").toString(), notifs, "writeNotif", "notifs", model);
                        
        } else {
            model.addAttribute("errormessage", " You need to be authenticated.");
            return "connection";
        }
        return "home";
    }
     
    /**
     * Generate the company account
     * @param companyInfo
     * @param model
     * @param session
     * @return 
     */
     @RequestMapping(value = "/generate", method = RequestMethod.POST)
     public String generateAccount (@ModelAttribute("SpringWeb") Company companyInfo  , ModelMap model, HttpSession session) {
        
        if (session.getAttribute("userID") != null ){ 
             System.out.println("Username=" + companyInfo.getUsernameComp());
             System.out.println("Name=" + companyInfo.getNameComp());
             System.out.println("Mail=" + companyInfo.getMailComp());
             System.out.println("Address=" + companyInfo.getAddressComp());
             System.out.println("Siret=" + companyInfo.getSiretComp());
             
             //Creation du compte de l'entreprise
             COMPANYTYPE newCompany = new COMPANYTYPE();
             newCompany.setNOM(companyInfo.getNameComp());
             newCompany.setMAIL(companyInfo.getMailComp());
             newCompany.setADDRESS(companyInfo.getAddressComp());
             newCompany.setSIRET(Integer.parseInt(companyInfo.getSiretComp()));
             
             int idNewComp = BusControl.genAccount(companyInfo.getUsernameComp(), newCompany);
             COMPANYTYPE company = BusControl.getCompanybyId(idNewComp);
             //Notification
             BusControl.creerNotification((int) session.getAttribute("userID"), (int) session.getAttribute("userID"), "New company account created for " + company.getNOM());
             
             int idUser = (int) session.getAttribute("userID");  
                    PERSONNELTYPE superv = BusControl.getPersonnelbyId(idUser);
                    NOTIFSTYPE test = BusControl.getNotifications(idUser);
                    int notifs = test.getNOTIFS().size();
                    // Traitement Superviseur
                    if (superv.isISADMIN()) {
                        LISTIDTYPE students = BusControl.getStudentsSupervisor(idUser);
                        List<Integer> studentsIds = students.getID();
                        ArrayList<Applications> listCan= new ArrayList<>();
                        
                        for (Integer studId : studentsIds) {
                            STUDENTTYPE stud = BusControl.getStudentbyId(studId);
                            Student student = new Student(studId,(String)stud.getFIRSTNAME(), (String)stud.getLASTNAME(), (String)stud.getMAIL(), (String)stud.getPHONENUMBER(), Integer.valueOf((String)stud.getSUPERVISORID()));
                            
                            APPLICATIONTYPE listCand = getApplications(studId);
                            if (listCand != null){
                                Iterator<APPLICATION> ite = listCand.getAPPLICATIONS().iterator();
                                
                                while (ite.hasNext()){
                                    APPLICATION offer = ite.next();
                                    
                                    
                                    int appId = offer.getApplicationID();
                                    int status = BusControl.getAppById(appId).getStatus();
                                    
                                    InternshipCompanyModel inte = BusControl.getOffersById(BusControl.getAppById(appId).getInternshipID());
                                    
                                    COMPANYTYPE com = BusControl.getCompanybyId(offer.getCompanyID());
                                    Applications can = new Applications(appId,student,inte, com.getNOM(), com.getMAIL(), com.getADDRESS(), Utils.getStatus(status));
                                    
                                    //If status est entre [8,11), on ajoute dans la liste des candidatures
                                    //int stat = BusControl.getAppById(can.getApplicationId()).getStatus();
                                    if (status >= 8 && status <11){
                                        listCan.add(can);
                                    }
                                    
                                }
                            }
                        }
                        model.addAttribute("listCan", listCan);
                        Utils.drawHomePage(session.getAttribute("userName").toString(), notifs, "generateAccount", "candidatureSupervisor", model);              
                    } else {
                        // Traitement administration
                        Utils.drawHomePage(session.getAttribute("userName").toString(), notifs, "accountAdministration", "conventionAdministration", model);
                    }
        } else {
            model.addAttribute("errormessage", " You need to be authenticated..");
            return "connection";
        }
        return "home";
    }     
    
    
}
